package com.wei.czz.common.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.wei.czz.common.utils.CopyUtils;
import com.wei.czz.common.vo.common.UploadVo;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2024-06-26 18:35:37
 * className: ObjectUploadListener
 * version: 1.0
 * description:
 */
@Getter
public class ObjectUploadListener<T extends UploadVo> implements ReadListener<T> {

    private static final Logger log = LoggerFactory.getLogger(ObjectUploadListener.class);

    /**
     * 解析成功数据列表
     */
    private final List<T> successList = new ArrayList<>();

    /**
     * 解析成功数据映射
     */
    private final Map<Integer, T> successMap = new HashMap<>();
    
    /**
     * 解析失败数据列表
     */
    private final List<T> failList = new ArrayList<>();

    @Override
    public void invoke(T uploadVo, AnalysisContext analysisContext) {
        // 校验上传字段是否存在错误
        String errorMessage = uploadVo.valid();;
        if (StringUtils.isBlank(errorMessage)) {
            // 收集数据
            successList.add(uploadVo);
            // 收集数据映射
            successMap.put(uploadVo.getSerial(), uploadVo);
        } else {
            uploadVo.setErrorMessage(errorMessage);
            // 收集数据
            failList.add(uploadVo);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("导入文件解析完成。total={} success.size={} fail.size={}",
                analysisContext.readRowHolder().getRowIndex(), successList.size(), failList.size());
        if (!successList.isEmpty()) {
            log.info("解析成功数据：{}", CopyUtils.mapList(successList, UploadVo::getSerial));
        }
        if (!failList.isEmpty()) {
            log.info("解析失败数据：{}", CopyUtils.mapList(failList, uploadVo -> uploadVo.getSerial() + "-" + uploadVo.getErrorMessage() + ";"));
        }
    }

    /**
     * 判断上传文件是否为空
     * @return true-空 false-非空
     */
    public boolean isEmpty() {
        return successList.isEmpty() && failList.isEmpty();
    }

    /**
     * 获取上传文件总行数
     * @return 上传文件总行数
     */
    public int getTotal() {
        return successList.size() + failList.size();
    }

}
